package com.tsn.controller;


import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tsn.common.Dto.LoginDto;
import com.tsn.common.Result;
import com.tsn.entity.Attention;
import com.tsn.entity.Role;
import com.tsn.entity.User;
import com.tsn.entity.UserRole;
import com.tsn.service.UserRoleService;
import com.tsn.service.UserService;
import com.tsn.util.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author tsn
 * @since 2021-07-08
 */
@RestController
@RequestMapping("/tsn/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    JwtUtils jwtUtils;

    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response) {
        System.out.println(loginDto);
        User user = userService.getOne(new QueryWrapper<User>().eq("user_name", loginDto.getUserName()));
//        Assert.notNull(user, "用户不存在");
        if(user==null)
            return Result.failure("用户不存在");
        if (!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))) {
            return Result.failure("密码不正确");
        }
        String jwt = jwtUtils.generateToken(user.getId());

        response.setHeader("Authorization", jwt);
        response.setHeader("Access-control-Expose-Headers", "Authorization");
        user.setLastLogin(LocalDateTime.now());
        userService.updateById(user);

        return Result.success(MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUserName())
                .put("avatar", user.getAvatar())
                .put("email", user.getEmail())
                .put("token", jwt)
                .put("lastlogin",user.getLastLogin())
                .map()
        );
    }
    @RequiresAuthentication
    @GetMapping("/getUserInfo")
    public  Result GetUserInfo(@RequestParam("username") String userName){
        System.out.println(userName);
        User userInfo = userService.getUserInfo(userName);
        if(userInfo==null)
            return Result.failure("验证失败");
        return Result.success(userInfo);
    }
    @RequiresAuthentication
    @GetMapping("/logout")
    public  Result logout(){
        SecurityUtils.getSubject().logout();
        return Result.success(null);
    }
    @RequiresAuthentication
    @GetMapping("/getUserList")
    public  Result GetUserList(){

        return userService.listUserInfos();
    }
    @GetMapping("/alreadyUsername")
    public Result alreadyUsername(@RequestParam("userName")String userName){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_name",userName);
        if(userService.count(userQueryWrapper)>0)
        {
            return Result.failure("已存在该用户名");
        }
        else{
            return Result.success(null);
        }
    }
    @PostMapping("/register")
    public Result register(@RequestBody JSONObject jsonObject){
        User user = JSON.toJavaObject(jsonObject, User.class);
        user.setAvatar("http://qz2emi6p8.hd-bkt.clouddn.com/avator.png");
        user.setPassword(SecureUtil.md5(user.getPassword()));
        userService.save(user);
        UserRole userRole = new UserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(3);
        userRoleService.save(userRole);
        return Result.success(null);

    }
    @GetMapping("getMyInfo")
    public Result getMyInfo(@RequestParam("userId")Integer id){
        return Result.success(userService.getById(id)) ;
    }
}

